//package com.plian.system.service.pm.listedcompany.impl;
//
//import com.alibaba.excel.EasyExcel;
//import com.alibaba.excel.read.listener.PageReadListener;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.metadata.IPage;
//import com.baomidou.mybatisplus.core.toolkit.Wrappers;
//import com.plian.Tools.CollectionUtil;
//import com.plian.Tools.DateUtil;
//import com.plian.Tools.StringUtil;
//import com.plian.system.bean.pm.FirmMainIndicatorsExcelBean;
//import com.plian.system.bean.pm.ListedFirmInfoExcelBean;
//import com.plian.system.bean.pm.TenShareHolderExcelBean;
//import com.plian.system.constant.sys.FormTypeConstant;
//import com.plian.system.constant.yth.YthConstant;
//import com.plian.system.entity.pm.listedcompany.FirmMainIndicators;
//import com.plian.system.entity.pm.listedcompany.ListedFirmInfo;
//import com.plian.system.entity.pm.listedcompany.TenShareHolders;
//import com.plian.system.entity.sys.Org;
//import com.plian.system.excel.ImportExcelUtil;
//import com.plian.system.mapper.pm.listedcompany.ListedFirmInfoMapper;
//import com.plian.system.model.CommonCode;
//import com.plian.system.model.ListResult;
//import com.plian.system.mybatis.base.BaseServiceImpl;
//import com.plian.system.mybatis.search.SearchEntity;
//import com.plian.system.mybatis.search.SearchParamEntiy;
//import com.plian.system.mybatis.search.TokenSearch;
//import com.plian.system.mybatis.support.Condition;
//import com.plian.system.mybatis.support.Query;
//import com.plian.system.service.pm.listedcompany.IFirmMainIndicatorsService;
//import com.plian.system.service.pm.listedcompany.IListedFirmInfoService;
//import com.plian.system.service.pm.listedcompany.ITenShareHoldersService;
//import com.plian.system.service.sys.orgzation.IOrgService;
//import com.plian.system.vo.pm.listedcompany.ListedFirmInfoVO;
//import com.plian.system.vo.yth.YthResult;
//import com.plian.system.wrapper.pm.listedcompany.ListedFirmInfoWrapper;
//import lombok.AllArgsConstructor;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang.exception.ExceptionUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.ByteArrayInputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.math.BigDecimal;
//import java.util.*;
//import java.util.stream.Collectors;
//
//
//@Service
//@AllArgsConstructor
//public class ListedFirmInfoServiceImpl extends BaseServiceImpl<ListedFirmInfoMapper, ListedFirmInfo> implements IListedFirmInfoService {
//
//    private ListedFirmInfoWrapper listedFirmInfoWrapper;
//
//    private ITenShareHoldersService tenShareHoldersService;
//
//    private IFirmMainIndicatorsService firmMainIndicatorsService;
//
//    private IOrgService orgService;
//
//
//    @Override
//    public boolean saveOrUpdate(ListedFirmInfo listedFirmInfo) {
//        if (!Optional.ofNullable(listedFirmInfo.getId()).isPresent()) {
//            listedFirmInfo.setFormType(String.valueOf(FormTypeConstant.QM_LISTED_INFORMATION));
//        }
//        return super.saveOrUpdate(listedFirmInfo);
//    }
//
//    @Override
//    public boolean deleteLogic(List<Long> ids) {
//        boolean result = super.deleteLogic(ids);
//        if (result){
//            tenShareHoldersService.deleteByParentId(ids);
//            firmMainIndicatorsService.deleteByParentId(ids);
//        }
//        return result;
//    }
//
//    @Override
//    public ListedFirmInfoVO getDetailObj(ListedFirmInfo listedFirmInfo) {
//        ListedFirmInfo detail = getOne(Condition.getQueryWrapper(listedFirmInfo));
//        ListedFirmInfoVO listedFirmInfoVO = listedFirmInfoWrapper.entityToVO(detail);
//
//        //主要指标
//        List<FirmMainIndicators> indicators = firmMainIndicatorsService.list(new LambdaQueryWrapper<FirmMainIndicators>().eq(FirmMainIndicators::getBaseFirmId, detail.getId())
//                .orderByDesc(FirmMainIndicators::getTime));
//        listedFirmInfoVO.setIndicators(indicators);
//        if (CollectionUtil.isNotEmpty(indicators)){
//            List<FirmMainIndicators> yearIndicators = new ArrayList<>();
//            indicators.forEach(m ->{
//                Optional.ofNullable(m.getTime()).ifPresent( time ->{
//                    m.setYear(DateUtil.format(m.getTime(),DateUtil.PATTERN_YEAR));
//                });
//            });
//            Map<String, List<FirmMainIndicators>> mapByYear = indicators.stream().filter(m-> Optional.ofNullable(m.getYear()).isPresent()).collect(Collectors.groupingBy(FirmMainIndicators::getYear));
//            for (String year:mapByYear.keySet()){
//                mapByYear.get(year).stream().max(Comparator.comparing(FirmMainIndicators::getTime)).ifPresent(yearIndicators::add);
//            }
//            yearIndicators = yearIndicators.stream().sorted(Comparator.comparing(FirmMainIndicators::getYear).reversed()).collect(Collectors.toList());
//            listedFirmInfoVO.setYearIndicators(yearIndicators);
//        }
//        //十大股东
//        List<TenShareHolders> shareHolders = tenShareHoldersService.list(new LambdaQueryWrapper<TenShareHolders>().eq(TenShareHolders::getBaseFirmId, detail.getId())
//                .orderByAsc(TenShareHolders::getSerialNumber));
//        listedFirmInfoVO.setShareHolders(shareHolders);
//
//        return listedFirmInfoVO;
//    }
//
//    @Override
//    @Transactional(rollbackFor=RuntimeException.class)
//    public boolean submit(ListedFirmInfo listedFirmInfo) {
//
//        Optional.ofNullable(listedFirmInfo.getListedFirmName()).ifPresent(firmName ->{
//            //删除老的
//            ListedFirmInfo oldFirm = getOne(Wrappers.<ListedFirmInfo>lambdaQuery().eq(ListedFirmInfo::getListedFirmName, firmName));
//            Optional.ofNullable(oldFirm).ifPresent(m ->{
//               deleteLogic(Collections.singletonList(oldFirm.getId()));
//            });
//            // 所属集团
//            Org firm = orgService.getOne(Wrappers.<Org>lambdaQuery().eq(Org::getName, firmName));
//            Optional.ofNullable(firm).ifPresent(org ->{
//                Org unit = orgService.getOne(Wrappers.<Org>lambdaQuery().eq(Org::getOrgCode, org.getOrgCode().substring(0, 8)));
//                listedFirmInfo.setUnitId(unit.getId());
//            });
//        });
//        boolean result = saveOrUpdate(listedFirmInfo);
//        if (result){
//            //主要指标
//            List<FirmMainIndicators> indicators = listedFirmInfo.getIndicators();
//            if (CollectionUtil.isNotEmpty(indicators)){
//                indicators.forEach(indicator ->{
//                    indicator.setBaseFirmId(listedFirmInfo.getId());
//                    firmMainIndicatorsService.saveOrUpdate(indicator);
//                });
//            }
//            //十大股东
//            List<TenShareHolders> shareHolders = listedFirmInfo.getShareHolders();
//            if (CollectionUtil.isNotEmpty(shareHolders)){
//                shareHolders.forEach(holder ->{
//                    holder.setBaseFirmId(listedFirmInfo.getId());
//                    tenShareHoldersService.saveOrUpdate(holder);
//                });
//            }
//        }
//        return result;
//    }
//
//    @Override
//    public ListResult<ListedFirmInfoVO> list(@RequestBody Query query) {
//        List<SearchEntity> entityList = query.getSearch();
//        if (query.getAscs()==null&&query.getDescs()==null){
//            query.setDescs("create_time");
//        }
//        QueryWrapper<ListedFirmInfo> queryWrapper = SearchParamEntiy.getQueryWrapper(
//                Condition.getQueryWrapper(new ListedFirmInfo()), entityList
//        );
//        TokenSearch<ListedFirmInfo> tokenSearch = new TokenSearch<>();
//		tokenSearch.addTokenQuery(queryWrapper, query);
//
//        IPage<ListedFirmInfo> pages = page(Condition.getPage(query), queryWrapper);
//        List<ListedFirmInfoVO> listedFirmInfoVOS = listedFirmInfoWrapper.entityToVO(pages.getRecords());
//        ListResult<ListedFirmInfoVO> listResult = new ListResult<>(CommonCode.SUCCESS);
//        listResult.setList(listedFirmInfoVOS);
//        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
//        return listResult;
//    }
//
//    @Override
//    public void uploadFile(MultipartFile multipartFile){
//        try {
//            byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream());
//            InputStream inputStream = new ByteArrayInputStream(bytes);
//            List<Object> listedFirms = new ArrayList<>();
//            List<Object> firmMains = new ArrayList<>();
//            List<Object> tenShares = new ArrayList<>();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(0).headRowNumber(1).head(ListedFirmInfoExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> listedFirms.addAll(list))).build());
//            inputStream.reset();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(1).headRowNumber(1).head(FirmMainIndicatorsExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> firmMains.addAll(list))).build());
//            inputStream.reset();
//            EasyExcel.read(inputStream).build()
//                    .read(EasyExcel.readSheet(2).headRowNumber(1).head(TenShareHolderExcelBean.class)
//                            .registerReadListener(new PageReadListener<>(list -> tenShares.addAll(list))).build());
//            ImportExcelUtil.filterEmpty(listedFirms);
//            ImportExcelUtil.filterEmpty(firmMains);
//            ImportExcelUtil.filterEmpty(tenShares);
//
//            List<ListedFirmInfo> allList = getAllList(listedFirms, firmMains, tenShares);
//            if (CollectionUtil.isNotEmpty(allList)){
//                allList.forEach(this::submit);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * @Description: //TODO ExcelBean 转换
//     * @Author: Take-off
//     * @Date: 2:29 PM 2023/4/24
//     * @Param: [listedFirms, firmMains, tenShares]
//     * @return: java.util.List<com.plian.system.entity.pm.listedcompany.ListedFirmInfo>
//     **/
//    private List<ListedFirmInfo> getAllList(List<Object> listedFirms,List<Object> firmMains,List<Object> tenShares){
//        List<ListedFirmInfo> listedFirmInfos = new ArrayList<>();
//        List<FirmMainIndicators> firmMainIndicators = new ArrayList<>();
//        List<TenShareHolders> tenShareHolders = new ArrayList<>();
//
//        for (Object object : listedFirms) {
//            ListedFirmInfoExcelBean excelBean = (ListedFirmInfoExcelBean) object;
//            ListedFirmInfo listedFirmInfo = new ListedFirmInfo();
//            listedFirmInfo.setListedFirmName(excelBean.getListedFirmName());
//            listedFirmInfo.setBondCodeId(excelBean.getBondCodeId());
//            listedFirmInfo.setAddress(excelBean.getAddress());
//            listedFirmInfos.add(listedFirmInfo);
//        }
//        for (Object object : firmMains) {
//            FirmMainIndicatorsExcelBean excelBean = (FirmMainIndicatorsExcelBean) object;
//            FirmMainIndicators firmMainIndicator = new FirmMainIndicators();
//            firmMainIndicator.setListedFirmName(excelBean.getListedFirmName());
//            if (StringUtil.isNotBlank(excelBean.getTime())){
//                firmMainIndicator.setTime(DateUtil.parse(excelBean.getTime(),DateUtil.PATTERN_DATE));
//            }
//            if (StringUtil.isNotBlank(excelBean.getSeasonStockPrice())){
//                firmMainIndicator.setSeasonStockPrice(new BigDecimal(excelBean.getSeasonStockPrice()));
//            }
//            firmMainIndicator.setMarketValue(excelBean.getMarketValue());
//            firmMainIndicator.setTotalAssets(excelBean.getTotalAssets());
//            firmMainIndicator.setBelongParentCompanyRoe(excelBean.getBelongParentCompanyRoe());
//            firmMainIndicator.setBelongParentCompanyAssets(excelBean.getBelongParentCompanyAssets());
//            firmMainIndicator.setTtm(excelBean.getTtm());
//            firmMainIndicator.setPb(excelBean.getPb());
//
//            firmMainIndicators.add(firmMainIndicator);
//        }
//        for (Object object : tenShares) {
//            TenShareHolderExcelBean excelBean = (TenShareHolderExcelBean) object;
//            TenShareHolders tenShareHolder = new TenShareHolders();
//            tenShareHolder.setListedFirmName(excelBean.getListedFirmName());
//            tenShareHolder.setFundName(excelBean.getFundName());
//            tenShareHolder.setShareTypeId(excelBean.getShareTypeId());
//            tenShareHolder.setSerialNumber(excelBean.getSerialNumber());
//            tenShareHolder.setShareAmount(excelBean.getShareAmount());
//            tenShareHolder.setShareChange(excelBean.getShareChange());
//            tenShareHolder.setShareProportion(excelBean.getShareProportion());
//            tenShareHolder.setInOrDeHolding(excelBean.getInOrDeHolding());
//
//            tenShareHolders.add(tenShareHolder);
//        }
//        if (CollectionUtil.isNotEmpty(firmMainIndicators)){
//            Map<String, List<FirmMainIndicators>> mapByName = firmMainIndicators.stream().filter(m -> Optional.ofNullable(m.getListedFirmName()).isPresent())
//                    .collect(Collectors.groupingBy(FirmMainIndicators::getListedFirmName));
//
//            if (CollectionUtil.isNotEmpty(listedFirmInfos)){
//                listedFirmInfos.forEach( m ->{
//                    m.setIndicators(mapByName.get(m.getListedFirmName()));
//                });
//            }
//        }
//        if (CollectionUtil.isNotEmpty(tenShareHolders)){
//            Map<String, List<TenShareHolders>> mapByName = tenShareHolders.stream().filter(m -> Optional.ofNullable(m.getListedFirmName()).isPresent())
//                    .collect(Collectors.groupingBy(TenShareHolders::getListedFirmName));
//            if (CollectionUtil.isNotEmpty(firmMainIndicators)){
//                listedFirmInfos.forEach( m ->{
//                    m.setShareHolders(mapByName.get(m.getListedFirmName()));
//                });
//            }
//        }
//        return listedFirmInfos;
//    }
//
//    @Override
//    public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
//        try {
//            String fname = "车辆信息导入模板";
//            os = response.getOutputStream();//取得输出流
//            response.reset();//清空输出流
//            //下面是对中文文件名的处理
//            response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
//            InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/listedFirmImport.xlsx");
//            fname = java.net.URLEncoder.encode(fname, "UTF-8");
//            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("UTF-8"), "UTF-8") + ".xlsx");
//
//            response.setContentType("application/msexcel");//定义输出类型
//            int len;
//            byte[] b = new byte[2048];
//            while ((len = inputStream.read(b)) != -1) {
//                os.write(b, 0, len);
//            }
//            response.setHeader("Content-Length", String.valueOf(inputStream.available()));
//
//            inputStream.close();
//            os.close();
//        }catch (Exception e){
//            log.error(ExceptionUtils.getFullStackTrace(e));
//        }
//    }
//
//    @Override
//    public String saveListedFirm(String data) {
//        YthResult ythResult = new YthResult();
//        //成功的id集合
//        List<String> successIds = new ArrayList<>();
//        //失败的id集合
//        List<String> failIds = new ArrayList<>();
//        //失败的原因
//        List<String> failReasons = new ArrayList<>();
//        //将json字符串转换成list
//        List<ListedFirmInfo> dataList = JSON.parseArray(data, ListedFirmInfo.class);
//
//        if (CollectionUtil.isNotEmpty(dataList)) {
//            Map<String, String> orgSourceMap = orgService.getSourceId();
//            //根据datasourceIds 查询出所有的数据
//            List<ListedFirmInfo> list = list(new LambdaQueryWrapper<ListedFirmInfo>().eq(ListedFirmInfo::getDataSource,YthConstant.DATA_NINGBO).in(ListedFirmInfo::getDataSourceId, dataList.stream().map(ListedFirmInfo::getDataSourceId).toArray()));
//
//            if (CollectionUtil.isNotEmpty(list)) {
//                //删除子集
//                List<Long> ids = list.stream().map(ListedFirmInfo::getId).collect(Collectors.toList());
//                firmMainIndicatorsService.deleteByParentId(ids);
//                tenShareHoldersService.deleteByParentId(ids);
//            }
//            for (ListedFirmInfo entity:dataList){
//                transfer(entity,orgSourceMap);
//                //id重复略过
//                if (CollectionUtil.isNotEmpty(list)){
//                    List<String> olIds = list.stream().map(ListedFirmInfo::getDataSourceId).collect(Collectors.toList());
//                    String dataSourceId = entity.getDataSourceId();
//                    //判断数据库中是否有数据
//                    if (olIds.contains(dataSourceId)){
//                        for (ListedFirmInfo oldEntity:list){
//                            successIds.add(dataSourceId);
//                            entity.setId(oldEntity.getId());
//                            entity.setDataSource(YthConstant.DATA_NINGBO);
//                            submit(entity);
//                            list.remove(oldEntity);
//                            break;
//                        }
//                    }else {
//                        //如果数据库中没有数据，就新增
//                        entity.setDataSource(YthConstant.DATA_NINGBO);
//                        submit(entity);
//                        successIds.add(entity.getDataSourceId());
//                    }
//                }else {
//                    //如果数据库中没有数据，就新增
//                    entity.setDataSource(YthConstant.DATA_NINGBO);
//                    submit(entity);
//                    successIds.add(entity.getDataSourceId());
//                }
//            }
//        }else {
//            failReasons.add("数据为空");
//        }
//        ythResult.setSuccessIds(successIds);
//        ythResult.setFailIds(failIds);
//        ythResult.setFailReason(StringUtils.join(failReasons, ";"));
//        //ythResult转换成json字符串
//        return JSON.toJSONString(ythResult);
//    }
//
//    private void transfer(ListedFirmInfo entity, Map<String, String> orgSourceMap) {
//        Optional.ofNullable(entity.getUnitId()).ifPresent(m ->
//                {
//                    String orgId = orgSourceMap.get(m);
//                    if (StringUtil.isNotBlank(orgId)) {
//                        entity.setUnitId(orgId);
//                        entity.setCreateCompanyId(orgId);
//                    }
//                }
//        );
//    }
//
//}
